/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.purpose.service.impl;

import com.google.common.base.Splitter;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.purpose.bean.JobsTemplateBean;
import com.koron.purpose.bean.ResponsibilitiesLibBean;
import com.koron.purpose.domain.*;
import com.koron.purpose.mapper.*;
import com.koron.purpose.service.api.JobsTemplateService;
import com.koron.purpose.utils.BusinessCode;
import com.koron.system.domain.DictData;
import com.koron.system.mapper.DictDataMapper;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.io.InputStream;
import java.text.NumberFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class JobsTemplateServiceImpl implements JobsTemplateService {

    private final static Logger logger= LoggerFactory.getLogger(JobsTemplateServiceImpl.class);
    @SuppressWarnings({"deprecation", "rawtypes"})
    @Override
    public MessageBean<?> insert(JobsTemplateBean bean, StaffBean user) {
        MessageBean<?> msg = MessageBean.create(0, "SUCCESS", void.class);
        Map checkMap = addCheck(bean);
        int code = (int) checkMap.get("code");
        String description = (String) checkMap.get("description");
        if (code != 0) {
            msg.setCode(code);
            msg.setDescription(description);
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            JobsTemplateMapper mapper = factory.getMapper(JobsTemplateMapper.class);
            /*Integer count = mapper.addVerification(bean.getName());
            if (count > 0) {
                factory.close(false);
                msg.setCode(35002);
                msg.setDescription("已存在相同名称岗位");
                return msg;
            }*/
            bean.setAddTime(new Date());
            bean.setAddUser(user.getCode());
            bean.setAddUserName(user.getName());
            bean.setUpdateTime(new Date());
            bean.setUpdateUser(user.getCode());
            bean.setUpdateUserName(user.getName());
            bean.setId(DefaultIdGenerator.getInstance().generateLongId());
            //定人定岗
            List<JobsTemplateTask> taskList = bean.getTaskList();
            for (JobsTemplateTask task : taskList) {
                task.setId(DefaultIdGenerator.getInstance().generateLongId());
                task.setTemplateId(bean.getId());
            }
            //证照要求
            List<JobsTemplateCertificate> certificateList = bean.getCertificateList();
            for (JobsTemplateCertificate certificate : certificateList) {
                certificate.setId(DefaultIdGenerator.getInstance().generateLongId());
                certificate.setTemplateId(bean.getId());
            }
            //培训要求
            List<JobsTemplateTraining> trainingList = bean.getTrainingList();
            for (JobsTemplateTraining training : trainingList) {
                training.setId(DefaultIdGenerator.getInstance().generateLongId());
                training.setTemplateId(bean.getId());
            }
            //危害因素
            List<JobsTemplateHazard> hazardList = bean.getHazardList();
            for (JobsTemplateHazard hazard : hazardList) {
                hazard.setId(DefaultIdGenerator.getInstance().generateLongId());
                hazard.setTemplateId(bean.getId());
            }
            if (!taskList.isEmpty()) {
                factory.getMapper(JobsTemplateTaskMapper.class).batchInsert(taskList);
            }
            if (!certificateList.isEmpty()) {
                factory.getMapper(JobsTemplateCertificateMapper.class).batchInsert(certificateList);
            }
            if (!trainingList.isEmpty()) {
                factory.getMapper(JobsTemplateTrainingMapper.class).batchInsert(trainingList);
            }
            if (!hazardList.isEmpty()) {
                factory.getMapper(JobsTemplateHazardMapper.class).batchInsert(hazardList);
            }
            mapper.insert(bean);
            // 新增 岗位模板-职责表
            if (!StringUtils.isEmpty(bean.getResponsibilitiesLibIds())) {
                List<String> ids = Splitter.on(",").omitEmptyStrings().trimResults().splitToList(bean.getResponsibilitiesLibIds());
                List<Map> rls = new LinkedList<>();
                Map map;
                for (String id : ids) {
                    map = new HashMap();
                    map.put("jobsTemplateId", bean.getId());
                    map.put("responsibilitiesLibId", id);
                    rls.add(map);
                }
                rls = rls.stream().distinct().collect(Collectors.toList());
                factory.getMapper(JobsTemplateMapper.class).batchInsertRL(rls);
            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            factory.close(false);
            msg.setCode(35001);
            msg.setDescription("数据库连接异常");
            return msg;
        }finally {
            if (null != factory) {
                factory.close();
            }
        }
        return msg;
    }

    @SuppressWarnings({"deprecation", "rawtypes"})
    @Override
    public MessageBean<?> update(JobsTemplateBean bean, StaffBean user) {
        MessageBean<?> msg = MessageBean.create(0, "SUCCESS", void.class);
        Map checkMap = addCheck(bean);
        int code = (int) checkMap.get("code");
        String description = (String) checkMap.get("description");
        if (code != 0) {
            msg.setCode(code);
            msg.setDescription(description);
            return msg;
        }
        if (StringUtils.isEmpty(bean.getId())) {
            msg.setCode(35002);
            msg.setDescription("参数校验异常");
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            JobsTemplateMapper mapper = factory.getMapper(JobsTemplateMapper.class);
           /* Integer count = mapper.updateVerification(bean.getName(), bean.getId());
            if (count > 0) {
                factory.close(false);
                msg.setCode(35002);
                msg.setDescription("已存在相同名称岗位");
                return msg;
            }*/
            bean.setUpdateTime(new Date());
            bean.setUpdateUser(user.getCode());
            bean.setUpdateUserName(user.getName());
            //定人定岗
            List<JobsTemplateTask> taskList = bean.getTaskList();
            for (JobsTemplateTask task : taskList) {
                task.setId(DefaultIdGenerator.getInstance().generateLongId());
                task.setTemplateId(bean.getId());
            }
            //证照要求
            List<JobsTemplateCertificate> certificateList = bean.getCertificateList();
            for (JobsTemplateCertificate certificate : certificateList) {
                certificate.setId(DefaultIdGenerator.getInstance().generateLongId());
                certificate.setTemplateId(bean.getId());
            }
            //培训要求
            List<JobsTemplateTraining> trainingList = bean.getTrainingList();
            for (JobsTemplateTraining training : trainingList) {
                training.setId(DefaultIdGenerator.getInstance().generateLongId());
                training.setTemplateId(bean.getId());
            }
            //危害因素
            List<JobsTemplateHazard> hazardList = bean.getHazardList();
            for (JobsTemplateHazard hazard : hazardList) {
                hazard.setId(DefaultIdGenerator.getInstance().generateLongId());
                hazard.setTemplateId(bean.getId());
            }
            //删除子表数据
            factory.getMapper(JobsTemplateTaskMapper.class).delete(bean.getId());
            factory.getMapper(JobsTemplateCertificateMapper.class).delete(bean.getId());
            factory.getMapper(JobsTemplateTrainingMapper.class).delete(bean.getId());
            factory.getMapper(JobsTemplateHazardMapper.class).delete(bean.getId());

            if (!taskList.isEmpty()) {
                factory.getMapper(JobsTemplateTaskMapper.class).batchInsert(taskList);
            }
            if (!certificateList.isEmpty()) {
                factory.getMapper(JobsTemplateCertificateMapper.class).batchInsert(certificateList);
            }
            if (!trainingList.isEmpty()) {
                factory.getMapper(JobsTemplateTrainingMapper.class).batchInsert(trainingList);
            }
            if (!hazardList.isEmpty()) {
                factory.getMapper(JobsTemplateHazardMapper.class).batchInsert(hazardList);
            }
            // 根据 岗位模板id 删除 岗位模板-职责表
            factory.getMapper(JobsTemplateMapper.class).deleteRLByTemplateId(bean.getId());
            // 新增 岗位模板-职责表
            if (!StringUtils.isEmpty(bean.getResponsibilitiesLibIds())) {
                List<String> ids = Splitter.on(",").omitEmptyStrings().trimResults().splitToList(bean.getResponsibilitiesLibIds());
                List<Map> rls = new LinkedList<>();
                Map map;
                for (String id : ids) {
                    map = new HashMap();
                    map.put("jobsTemplateId", bean.getId());
                    map.put("responsibilitiesLibId", id);
                    rls.add(map);
                }
                rls = rls.stream().distinct().collect(Collectors.toList());
                factory.getMapper(JobsTemplateMapper.class).batchInsertRL(rls);
            }
            mapper.update(bean);
            factory.close();
        } catch (Exception e) {
            factory.close(false);
            msg.setCode(35001);
            msg.setDescription("数据库连接异常");
            return msg;
        }finally {
            if (null != factory) {
                factory.close();
            }
        }
        return msg;
    }

    @SuppressWarnings("deprecation")
    @Override
    public MessageBean<?> delete(String id) {
        MessageBean<?> msg = MessageBean.create(0, "success", void.class);
        JobsTemplateBean bean = queryById(id);
        if (bean == null) {
            msg.setCode(35002);
            msg.setDescription("参数校验异常");
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            factory.getMapper(JobsTemplateMapper.class).delete(id);
            factory.getMapper(JobsTemplateTaskMapper.class).delete(id);
            factory.getMapper(JobsTemplateCertificateMapper.class).delete(id);
            factory.getMapper(JobsTemplateTrainingMapper.class).delete(id);
            factory.getMapper(JobsTemplateHazardMapper.class).delete(id);
            // 根据 岗位模板id 删除 岗位模板-职责表
            factory.getMapper(JobsTemplateMapper.class).deleteRLByTemplateId(id);
            factory.close();
        } catch (Exception e) {
            factory.close(false);
            msg.setCode(35001);
            msg.setDescription("数据库连接异常");
        }
        return msg;
    }

    @Override
    public MessageBean<?> details(String id) {
        MessageBean<JobsTemplateBean> msg = MessageBean.create(0, "success", JobsTemplateBean.class);
        JobsTemplateBean bean = queryById(id);
        msg.setData(bean);
        return msg;
    }

    @SuppressWarnings({"deprecation", "unchecked", "rawtypes"})
    @Override
    public MessageBean<?> list(String corpCode, String corpName, String name, String code, String jobType, Integer page, Integer pageSize) {
        MessageBean<DataBean> msg = MessageBean.create(0, "SUCCESS", DataBean.class);
        Integer totalPage = null;
        Integer totalNumber = null;
        Integer start = null;
        Integer end = null;
        if (null != page && pageSize != null) {
            if (page > 0 && pageSize > 0) {
            } else {
                //第一页 10条数据
                page = 1;
                pageSize = 10;
            }
            start = (page <= 1) ? 0 : (page - 1) * pageSize;
            end = pageSize;
        }
        if (name != null) {
            name = "%" + name + "%";
        } else {
            name = "%%";
        }
        try (SessionFactory factory = new SessionFactory();) {
            totalNumber = factory.getMapper(JobsTemplateMapper.class).count(corpCode, corpName, name);
            if (start != null && end != null) {
                totalPage = (totalNumber + pageSize - 1) / pageSize;
            } else {
                totalPage = 1;
                page = totalPage;
                pageSize = totalNumber;
            }
            DataBean data = new DataBean();
            data.setList(queryList(corpCode, corpName, name, code, jobType, start, end));
            data.setPageNo(page);
            data.setPageSize(pageSize);
            data.setTotalNumber(totalNumber);
            data.setTotalPage(totalPage);
            msg.setData(data);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(35001);
            msg.setDescription("数据库连接异常");
            return msg;
        }
        return msg;
    }

    @SuppressWarnings({"deprecation", "unchecked", "rawtypes"})
    @Override
    public MessageBean<?> querySelectData(String name, String code, String jobType, Integer page, Integer pageSize) {
        MessageBean<DataBean> msg = MessageBean.create(0, "SUCCESS", DataBean.class);
        Integer totalPage = null;
        Integer totalNumber = null;
        Integer start = null;
        Integer end = null;
        if (null != page && pageSize != null) {
            if (page > 0 && pageSize > 0) {
            } else {
                //第一页 10条数据
                page = 1;
                pageSize = 10;
            }
            start = (page <= 1) ? 0 : (page - 1) * pageSize;
            end = pageSize;
        }
        if (!StringUtils.isEmpty(name)) {
            name = "%" + name + "%";
        } else {
            name = null;
        }
        try (SessionFactory factory = new SessionFactory();) {
            totalNumber = factory.getMapper(JobsTemplateMapper.class).count(null, null, name);
            if (start != null && end != null) {
                totalPage = (totalNumber + pageSize - 1) / pageSize;
            } else {
                totalPage = 1;
                page = totalPage;
                pageSize = totalNumber;
            }
            DataBean data = new DataBean();
            data.setList(querySelectList(name, code, jobType, start, end));
            data.setPageNo(page);
            data.setPageSize(pageSize);
            data.setTotalNumber(totalNumber);
            data.setTotalPage(totalPage);
            msg.setData(data);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(35001);
            msg.setDescription("数据库连接异常");
            return msg;
        }
        return msg;
    }

    @Override
    public MessageBean<?> dutyTemplateCetificateMatrix(String corpCode, String templateName, Integer start, Integer rows) {
        MessageBean<LinkedHashMap> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), LinkedHashMap.class);
        try (SessionFactory factory = new SessionFactory()) {
            LinkedHashMap<String, Object> map = new LinkedHashMap<>();
            List<DictData> ddlist = factory.getMapper(DictDataMapper.class).queryAll(null, "certificate_type", null, null);
            if (null == ddlist || ddlist.size() <= 0) {
                return msg;
            }
            List<String> nameList = ddlist.stream().map(DictData::getDictLabel).collect(Collectors.toList());
            map.put("nameList", nameList);
            List<LinkedHashMap<String, Object>> list = factory.getMapper(JobsTemplateCertificateMapper.class).queryDutyTemplateCetificate(corpCode,ddlist, templateName, start, rows);
            Integer totalNumber = factory.getMapper(JobsTemplateMapper.class).count(corpCode, null, StringUtils.isEmpty(templateName) ? null : "%" + templateName + "%");
            rows = (rows == null || rows <= 0) ? 1 : rows;
            Integer totalPage = totalNumber > rows ? (totalNumber % rows == 0) ? totalNumber / rows : totalNumber / rows + 1 : 1;
            map.put("totalNumber", totalNumber);
            map.put("totalPage", totalPage);
            map.put("pageNo", start == null || start == 0 ? 1 : start / rows);
            map.put("pageSize", rows);
            map.put("matrix", list);
            msg.setData(map);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(35001);
            msg.setDescription("数据库连接异常");
            return msg;
        }
    }


    @Override
    public MessageBean<?> dutyTemplatehazardMatrix(String corpCode, String templateName, Integer page, Integer pageSize) {
        MessageBean<LinkedHashMap> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), LinkedHashMap.class);
        try (SessionFactory factory = new SessionFactory()) {
            Integer totalPage = null;
            Integer totalNumber = null;
            Integer start = null;
            Integer end = null;
            if (null != page && pageSize != null) {
                if (page > 0 && pageSize > 0) {
                } else {
                    //第一页 10条数据
                    page = 1;
                    pageSize = 10;
                }
                start = (page <= 1) ? 0 : (page - 1) * pageSize;
                end = pageSize;
            }
            if (!StringUtils.isEmpty(templateName)) {
                templateName = "%" + templateName + "%";
            }
            totalNumber = factory.getMapper(JobsTemplateMapper.class).count(corpCode, null, templateName);
            if (start != null && end != null) {
                totalPage = (totalNumber + pageSize - 1) / pageSize;
            } else {
                totalPage = 1;
                page = totalPage;
                pageSize = totalNumber;
            }
            LinkedHashMap retMap = new LinkedHashMap<>();
            retMap.put("totalPage", totalPage);
            retMap.put("totalNumber", totalNumber);
            retMap.put("pageNo", page);
            retMap.put("pageSize", pageSize);

            List<String> noteList = factory.getMapper(JobsTemplateHazardMapper.class).queryAllNote();
            List<JobsTemplateBean> list = factory.getMapper(JobsTemplateMapper.class).list(corpCode, null, templateName, null, null, start, pageSize);
            List<List<String>> retList = new ArrayList<>();
            List<String> jobIds = new ArrayList<>();
            if (noteList.isEmpty() && !list.isEmpty()) {
                List<String> jobsName = list.stream().map(JobsTemplateBean::getName).collect(Collectors.toList());
                retList.add(jobsName);
                retMap.put("matrix", new ArrayList<>());
                retMap.put("noteList", new ArrayList());
                msg.setData(retMap);
                return msg;
            }
            if (!noteList.isEmpty() && list.isEmpty()) {
                retMap.put("matrix", new ArrayList());
                retMap.put("noteList", noteList);
                msg.setData(retMap);
                return msg;
            }
            jobIds = list.stream().map(JobsTemplateBean::getId).collect(Collectors.toList());
            List<LinkedHashMap<String, Object>> result = factory.getMapper(JobsTemplateHazardMapper.class).hazardMatrix(noteList, jobIds);
            for (LinkedHashMap<String, Object> map : result) {
                List jobsValue = new ArrayList<>();
                jobsValue.add(map.get("jobName"));
                for (String note : noteList) {
                    jobsValue.add(map.get(note));
                }
                retList.add(jobsValue);
            }
            retMap.put("noteList", noteList);
            retMap.put("matrix", retList);
            msg.setData(retMap);
            return msg;
        } catch (Exception e) {
            msg.setCode(35001);
            msg.setDescription("数据库连接异常");
            return msg;
        }
    }

    @Override
    public MessageBean<LinkedHashMap> exportDutyTemplatehazardMatrix(String corpCode, String templateName) {
        MessageBean<LinkedHashMap> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), LinkedHashMap.class);
        try (SessionFactory factory = new SessionFactory()) {
            LinkedHashMap retMap = new LinkedHashMap<>();
            List<String> noteList = factory.getMapper(JobsTemplateHazardMapper.class).queryAllNote();
            List<JobsTemplateBean> list = factory.getMapper(JobsTemplateMapper.class).list(corpCode, null, templateName, null, null, null, null);
            List<List<String>> retList = new ArrayList<>();
            List<String> jobIds = new ArrayList<>();
            if (noteList.isEmpty() && !list.isEmpty()) {
                List<String> jobsName = list.stream().map(JobsTemplateBean::getName).collect(Collectors.toList());
                retList.add(jobsName);
                retMap.put("matrix", retList);
                retMap.put("noteList", new ArrayList());
                msg.setData(retMap);
                return msg;
            }
            if (!noteList.isEmpty() && list.isEmpty()) {
                retMap.put("matrix", new ArrayList());
                retMap.put("noteList", noteList);
                msg.setData(retMap);
                return msg;
            }
            jobIds = list.stream().map(JobsTemplateBean::getId).collect(Collectors.toList());
            List<LinkedHashMap<String, Object>> result = factory.getMapper(JobsTemplateHazardMapper.class).hazardMatrix(noteList, jobIds);
            for (LinkedHashMap<String, Object> map : result) {
                List jobsValue = new ArrayList<>();
                jobsValue.add(map.get("jobName"));
                for (String note : noteList) {
                    jobsValue.add(map.get(note));
                }
                retList.add(jobsValue);
            }
            retMap.put("noteList", noteList);
            retMap.put("matrix", retList);
            msg.setData(retMap);
            return msg;
        } catch (Exception e) {
            msg.setCode(35001);
            msg.setDescription("数据库连接异常");
            return msg;
        }
    }


    @SuppressWarnings("deprecation")
    public JobsTemplateBean queryById(String id) {
        JobsTemplateBean bean;
        try (SessionFactory factory = new SessionFactory();) {
            bean = factory.getMapper(JobsTemplateMapper.class).queryById(id);
            if (bean == null) {
                return bean;
            }
            bean.setTaskList(factory.getMapper(JobsTemplateTaskMapper.class).queryByTid(id));
            bean.setCertificateList(factory.getMapper(JobsTemplateCertificateMapper.class).queryByTid(id));
            bean.setTrainingList(factory.getMapper(JobsTemplateTrainingMapper.class).queryByTid(id));
            bean.setHazardList(factory.getMapper(JobsTemplateHazardMapper.class).queryByTid(id));
            // 根据 岗位模板id 查询 岗位模板-职责
            bean.setResponsibilitieList(factory.getMapper(JobsTemplateMapper.class).getResponsibilitiesLibs(id));
        }
        return bean;
    }

    @SuppressWarnings("deprecation")
    public List<JobsTemplateBean> queryList(String corpCode, String corpName, String name, String code, String jobType, Integer start, Integer row) {
        List<JobsTemplateBean> list;
        try (SessionFactory factory = new SessionFactory();) {
            list = factory.getMapper(JobsTemplateMapper.class).list(corpCode, corpName, name, code, jobType, start, row);
            if (list.isEmpty()) {
                return list;
            }
            // 数据字典，查询 岗位模板-类型
            JobsTemplateTaskMapper jobsTemplateTaskMapper = factory.getMapper(JobsTemplateTaskMapper.class);
            JobsTemplateCertificateMapper jobsTemplateCertificateMapper = factory.getMapper(JobsTemplateCertificateMapper.class);
            JobsTemplateTrainingMapper jobsTemplateTrainingMapper = factory.getMapper(JobsTemplateTrainingMapper.class);
            JobsTemplateHazardMapper jobsTemplateHazardMapper = factory.getMapper(JobsTemplateHazardMapper.class);
            // 获取 岗位模板类型
            List<DictData> dicts = factory.getMapper(DictDataMapper.class).queryAll(null, "jobs_template_job_type", null, null);
            List<ResponsibilitiesLibBean> responsibilitiesLibBeans;
            for (JobsTemplateBean bean : list) {
                // 获取类型名称
                Optional.ofNullable(bean.getJobType()).ifPresent(type -> {
                    dicts.stream().forEach(dict -> {
                        if (type.equals(dict.getId())) {
                            bean.setJobTypeName(dict.getDictLabel());
                            return;
                        }
                    });
                });
                bean.setTaskList(jobsTemplateTaskMapper.queryByTid(bean.getId()));
                bean.setCertificateList(jobsTemplateCertificateMapper.queryByTid(bean.getId()));
                bean.setTrainingList(jobsTemplateTrainingMapper.queryByTid(bean.getId()));
                bean.setHazardList(jobsTemplateHazardMapper.queryByTid(bean.getId()));
                // 根据 岗位模板id 查询 岗位模板-职责
                responsibilitiesLibBeans = factory.getMapper(JobsTemplateMapper.class).getResponsibilitiesLibs(bean.getId());
                StringBuffer sb = new StringBuffer();
                if (responsibilitiesLibBeans != null && responsibilitiesLibBeans.size() > 0) {
                    for (int i = 0, size = responsibilitiesLibBeans.size(); i < size; i++) {
                        sb.append((i + 1) + ".");
                        if (i == size - 1) {
                            sb.append(responsibilitiesLibBeans.get(i).getItem());
                        } else {
                            sb.append(responsibilitiesLibBeans.get(i).getItem() + "\n");
                        }
                    }
                }
                bean.setNote(sb.toString());
                bean.setResponsibilitieList(responsibilitiesLibBeans);

            }
        }
        return list;

    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    private Map addCheck(JobsTemplateBean bean) {
        Map map = new HashMap();
        if (bean == null) {
            map.put("code", 35002);
            map.put("description", "请填写岗位信息");
            return map;
        }
        if (StringUtils.isEmpty(bean.getName())) {
            map.put("code", 35002);
            map.put("description", "岗位名称不能为空");
            return map;
        }
        if (StringUtils.isEmpty(bean.getNote())) {
            map.put("code", 35002);
            map.put("description", "岗位职责描述不能为空");
            return map;
        }
        if (bean.getSerial() == null) {
            map.put("code", 35002);
            map.put("description", "排序号不能为空");
            return map;
        }
        //定人定岗
        List<JobsTemplateTask> taskList = bean.getTaskList();
        int row = 1;
        for (JobsTemplateTask task : taskList) {
            if (StringUtils.isEmpty(task.getTaskTypeId())) {
                map.put("code", 35002);
                map.put("description", "定人定岗：行+" + row + "任务类型不能为空");
                return map;
            }
            if (StringUtils.isEmpty(task.getTaskObjectId())) {
                map.put("code", 35002);
                map.put("description", "定人定岗：行+" + row + "任务对象不能为空");
                return map;
            }
            if (StringUtils.isEmpty(task.getNote())) {
                map.put("code", 35002);
                map.put("description", "定人定岗：行+" + row + "任务描述不能为空");
                return map;
            }
            if (StringUtils.isEmpty(task.getCycleId())) {
                map.put("code", 35002);
                map.put("description", "定人定岗：行+" + row + "周期不能为空");
                return map;
            }
            row++;
        }
        row = 1;
        //证照要求
        List<JobsTemplateCertificate> certificateList = bean.getCertificateList();
        for (JobsTemplateCertificate certificate : certificateList) {
            if (StringUtils.isEmpty(certificate.getCertificateTypeId())) {
                map.put("code", 35002);
                map.put("description", "证照要求：行+" + row + "证照名称不能为空");
                return map;
            }
            if (StringUtils.isEmpty(certificate.getAuthorization())) {
                map.put("code", 35002);
                map.put("description", "证照要求：行+" + row + "授权类型不能为空");
                return map;
            }
            row++;
        }
        row = 1;
        //培训要求
        List<JobsTemplateTraining> trainingList = bean.getTrainingList();
        for (JobsTemplateTraining training : trainingList) {
            if (StringUtils.isEmpty(training.getTrainingTypeId())) {
                map.put("code", 35002);
                map.put("description", "培训要求：行+" + row + "培训类型不能为空");
                return map;
            }
            if (StringUtils.isEmpty(training.getCycleId())) {
                map.put("code", 35002);
                map.put("description", "培训要求：行+" + row + "培训周期不能为空");
                return map;
            }
            if (training.getDuration() == null) {
                map.put("code", 35002);
                map.put("description", "培训要求：行+" + row + "培训时长不能为空");
                return map;
            }
            row++;
        }
        row = 1;
        //危害因素
        List<JobsTemplateHazard> hazardList = bean.getHazardList();
        for (JobsTemplateHazard hazard : hazardList) {
            if (StringUtils.isEmpty(hazard.getNote())) {
                map.put("code", 35002);
                map.put("description", "危害因素：行+" + row + "描述不能为空");
                return map;
            }
            row++;
        }
        map.put("code", 0);
        map.put("description", "校验成功");
        return map;
    }

    private List<JobsTemplateBean> querySelectList(String name, String code, String jobType, Integer start, Integer row) {
        List<JobsTemplateBean> list;
        try (SessionFactory factory = new SessionFactory();) {
            list = factory.getMapper(JobsTemplateMapper.class).list(null, null, name, code, jobType, start, row);
        }
        return list;

    }

    @Override
    public MessageBean<String> importExcel(StaffBean user, MultipartFile file) {
        MessageBean<String> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), String.class);
        try (SessionFactory factory = new SessionFactory()) {
            if (null == file) {
                msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
                msg.setDescription("未上传文件");
                return msg;
            }
            InputStream inputStream = file.getInputStream();
            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
            if (null == workbook) {
                msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
                msg.setDescription("上传文件为空");
                return msg;
            }
            XSSFSheet sheet = workbook.getSheetAt(0);
            if (null == sheet) {
                msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
                msg.setDescription("上传文件为空");
                return msg;
            }
            List<JobsTemplate> templateList = new ArrayList<>();
            int rowNumber = sheet.getPhysicalNumberOfRows();
            Date date = new Date();
            int count = factory.getMapper(JobsTemplateMapper.class).count(null, null, null);
            NumberFormat numberFormat = NumberFormat.getNumberInstance();
            numberFormat.setMaximumIntegerDigits(5);//最大位数
            numberFormat.setGroupingUsed(false);
            int temp = 0;
            for (int i = 1; i < rowNumber; i++) {
                XSSFRow row = sheet.getRow(i);
                if (row == null) {
                    temp++;
                    continue;
                }
                String name = getCellValue(row.getCell(0));
                if (StringUtils.isEmpty(name)) {
                    temp++;
                    continue;
                }
                JobsTemplate template = new JobsTemplate();
                int code = count + i - temp;
                template.setCode(numberFormat.format(code));
                template.setSerial(code);
                template.setName(name);
                template.setId(DefaultIdGenerator.getInstance().generateLongId());
                template.setAddTime(date);
                template.setAddUser(user.getCode());
                template.setAddUserName(user.getName());
                template.setUpdateTime(date);
                template.setUpdateUser(user.getCode());
                template.setUpdateUserName(user.getName());
                template.setCorpCode(user.getDepartmentCode());
                templateList.add(template);
            }
            if (null != templateList && templateList.size() > 0) {
                factory.getMapper(JobsTemplateMapper.class).batchInsertJobsTemplate(templateList);
            }
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    /**
     * 获取单元格的值
     *
     * @param cell
     * @return
     */
    @SuppressWarnings("deprecation")
    public String getCellValue(XSSFCell cell) {
        if (cell == null) {
            return "";
        }
        if (cell.getCellTypeEnum() == CellType.STRING) {
            return cell.getStringCellValue();
        } else if (cell.getCellTypeEnum() == CellType.BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellTypeEnum() == CellType.FORMULA) {
            return cell.getCellFormula();
        } else if (cell.getCellTypeEnum() == CellType.NUMERIC) {
            return String.valueOf(cell.getNumericCellValue());
        } else {
            return "";
        }
    }
}
